const app = getApp();
var util = require('../util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {

    nowDate: '',
    nowTime: '',
    btn: '更多记录',
    //签到模块
    signNum: 0, //签到数
    signState: false, //签到状态   
    networkType: 'wifi',
    latitude: '',//坐标
    longitude: '',//坐标
    shareshow: true,
    btd: true,
    page: 1,
    btnname: "工作签到",
    btbname: "休息签到",
    btn_h: false,
  },
  onLoad: function () {
    var that = this;
    this.onList();
    this.GetSet();
    //this.GetSignin();    
    wx.getNetworkType({
      success(res) {
        that.setData({
          networkType: res.networkType
        });
      }
    });
    //this.getLocation();
    this.setData({
      nowDate: util.formatDate(new Date()),
      nowTime: util.formattime(new Date())
    });



    setInterval(function () {
      that.setData({
        nowTime: util.formattime(new Date())
      });
    }, 1000);
  },
  //签到
  bindSignIn(e) {
    var m = new Date().getMinutes().toString();
    if (m == wx.getStorageSync('m')) {     
      wx.showToast({
        icon: 'none',
        title: '请稍等1分钟后再提交！',
      });
      return false;
    }
    wx.setStorageSync('m', m)
    var that = this,
      num = e.currentTarget.dataset.num;
    num++
    wx.showToast({
      icon: 'success',
      title: '签到成功',
    })
    that.setData({
      signNum: num,
      btnname: "提交中",
      btbname: "提交中",

      //signState: true
    })

    var min = e.currentTarget.dataset.min,
      max = e.currentTarget.dataset.max,
      be = e.currentTarget.dataset.be;

    if (num % 7 == 0) {
      be += 1;
      that.setData({
        be: be
      })
    }

    if (num == 7 * be + 1) {
      that.setData({
        min: 7 * be + 1,
        max: 7 * be + 7
      })
    }
    this.Signin_it(e);
  },
  GetSignin: function (e) {
    var that = this;
    wx.cloud.callFunction({
      name: 'Get_fun',
      data: {
        data: '{"[]": {"K_W_Signin": { "Openid":"' + getApp().globalData.openid + '","Memo$": "' + util.formatDate(new Date()) + '%","@column":"TypeName,CreateDate"}}}'
      },
      success: res => {
        let obj = JSON.parse(res.result)["[]"];
        //   that.setData({ list: obj }),
        //      console.log(obj.length);
        if (obj.length <= 1) {
          that.setData({
            shareshow: false
          })
        }
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err);
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
      }
    })
  },
  Signin_it: function (e) {
    var that = this;
    wx.getNetworkType({
      success(res) {
        that.setData({
          networkType: res.networkType
        });
      }
    })

    let data = '{"K_W_Signin": {"TypeName":"' + e.currentTarget.dataset.state + '","Memo":"' + util.formatDate(new Date()) + '","Openid":"' + getApp().globalData.openid + '","Name":"' + getApp().globalData.name + '","Creatorid":"' + getApp().globalData.appid + '","longitude":"' + this.data.longitude + '","latitude":"' + this.data.latitude + '","network":"' + this.data.networkType + '"}}';
    console.log(data);
    wx.cloud.callFunction({
      name: 'Add_fun',
      data: {
        data: util.encode(util.encodeUTF8(data))
      },
      success: res => {
        var chday = this.Checkday(util.formatDate(new Date()) + "报岗");
        if (chday) {
          wx.showModal({
            title: '签到成功',
            content: '是否进行报岗',
            success(res) {
              let url = '../console/Index'
              if (res.confirm) {
                url = '../work_log/Index?title=' + util.formatDate(new Date()) + '报岗'
              }
              wx.redirectTo({ url: url })
            }
          })
        }
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
        console.error('[云函数] [openapi] Add_fun 调用失败：', err)
      }
    })
  },
  onList: function (e) {
    var that = this;
    if (this.data.page == 1) {
      this.setData({ list: [] });
    }
    var that = this, data = '', data_name = 'K_W_Signin', data_json = '"page": ' + this.data.page + ',"count": 15,';
    data_json = data_json + '"Openid": "' + getApp().globalData.openid + '",';
    data_json = data_json + '"@column":"TypeName,CreateDate","@order": "CreateDate-"';
    data = '{"[]":{"query":2,"' + data_name + '": { ' + data_json + '}},"total@":"/[]/total"}';
    console.log(data);
    wx.cloud.callFunction({
      name: 'Get_fun',
      data: {
        data: data
      },
      success: res => {
        console.log(res.result);
        let obj = JSON.parse(res.result);
        that.setData({ list: this.data.list.concat(obj["[]"]) });
        //sl=当前记录数、dsl=总记录数
        let sl = that.data.list.length, dsl = obj["total"];
        if (sl == dsl) {
          that.setData({ shareshow: true, btn: "加载完成", btn_h: true })
        } else {
          that.setData({ page: that.data.page + 1 })
        }
        wx.hideLoading({
          complete: (res) => { },
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err);
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
      }
    })
  },
  getLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        that.GetSignin();
      }
    });
  },
  GetSet: function () {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '授权失败',
                  icon: 'success',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用getLocationt的API
                      that.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 1000
                      })

                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入
          that.getLocation();
        }
        else { //授权后默认加载
          that.getLocation();
        }

      }
    })
  },

  Checkday: function (cd) {
    var rt = true;
    var data = '{"[]":{"K_W_Record":{"Openid":"' + getApp().globalData.openid + '","Name":"' + cd + '"}}}';
    console.log(data)
    wx.cloud.callFunction({
      name: 'Get_fun',
      data: {
        data: data
      },
      success: res => {
        let obj = JSON.parse(res.result)["[]"];
        console.log(obj.length);
        if (obj.length > 0) {
          wx.showModal({
            showCancel: false,
            icon: '信息提示',
            title: cd + '已经报岗！',
          })
        } else {
          rt = false;
        };
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err);
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
      }
    })
    return rt;
  },

  formatIDate: function (strTime) {
    if (!strTime) {
      return '';
    }
    var myDate = new Date(strTime + '+0800');
    if (myDate == 'Invalid Date') {
      strTime = strTime.replace(/T/g, ' '); //去掉T
      strTime = strTime.replace(/-/g, '/');
      strTime = strTime.replace(/\.\d+/, ' '); //去掉毫秒
      myDate = new Date(strTime + '+0800');
    }
    var d = new Date(myDate);
    let y = d.getFullYear()
    let m = (d.getMonth() + 1)
    m = m < 10 ? ('0' + m) : m;
    let day = d.getDate() < 10 ? (`0${d.getDate()}`) : d.getDate()
    let h = d.getHours() < 10 ? (`0${d.getHours()}`) : d.getHours()
    let minute = d.getMinutes() < 10 ? (`0${d.getMinutes()}`) : d.getMinutes()
    let second = d.getSeconds() < 10 ? (`0${d.getSeconds()}`) : d.getSeconds()


    d = `${y}年${m}月${day} 日 ${h}时${minute}分`
   console.log(d);
    return d;
  }
})